import { getDicByKey } from '@/support/common';
import { Card, Table } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import Ellipsis from '../../../components/Ellipsis';

const mapStateToProps = (state: any) => ({
  type: state.type,
  loading: state.loading.effects['type/getFetchPage'],
});
class Type extends PureComponent<any, any> {
  static contextTypes = {
    dicData: PropTypes.any,
  };

  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      visible: false,
      checkedKeys: {},
      expandedKeys: [],
      roleData: {},
      isView: false,
      isAdd: false,
      judgeData: [],
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'type/getDataWithRes',
    //   payload: { url: '/basedata/findredisdata', type: 'series' },
    //   callback: response => {
    //     this.state.judgeData = response.vehicleSeriesList;
    //     console.log('judgeData', this.state.judgeData);

    //     dispatch({
    //       type: 'type/getFetchPage',
    //       payload: { url: '/basedata/type' },
    //     });
    //   },
    // });
  }
  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'type/getDataWithRes',
      payload: { url: '/basedata/findredisdata', type: 'series' },
      callback: response => {
        this.setState({
          judgeData: response.vehicleSeriesList,
        });
      },
    });
    const brandId1 = { brandId: this.searchForm.current?.getFieldValue('brandId') };
    this.setState({
      formValues: Object.assign(this.state.formValues, brandId1),
    });
    dispatch({
      type: 'type/getFetchPage',
      payload: { url: '/basedata/type', ...brandId1 },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'type/initData',
    });
  }
  handleFormReset = () => {
    this.searchForm.current.setFieldsValue({ brandId: 'MATC' });
    this.setState({
      formValues: {
        brandId: this.searchForm.current?.getFieldValue('brandId'),
      },
    });
  };
  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      page: current - 1,
      size: pageSize,
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'type/getFetchPage',
      payload: { url: '/basedata/type', ...params },
    });
  };
  handleSeriesCode = val => {
    let str = val;
    let judgeList = this.state.judgeData.filter(x => {
      return x.code === val;
    });
    if (judgeList[0]) {
      str = judgeList[0].name;
    }

    return (
      <Ellipsis length={20} tooltip>
        {str}
      </Ellipsis>
    );
  };
  render() {
    const {
      type: {
        pageData: { list, pagination },
      },
      loading,
    } = this.props;
    const { formValues } = this.state;
    const columns = [
      {
        title: '品牌',
        dataIndex: 'brandId',
        // render: val =>
        //   val === 'MATC' ? (
        //     <Ellipsis length={10} tooltip>
        //       猛士科技
        //     </Ellipsis>
        //   ) : val === 'DFPV' ? (
        //     <Ellipsis length={10} tooltip>
        //       东风勇士
        //     </Ellipsis>
        //   ) : null,
        render: text => {
          if (text) {
            return getDicByKey(this.context.dicData, 'optBrand', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '车系',
        dataIndex: 'seriesCode',
        render: val => this.handleSeriesCode(val),
      },
      {
        title: '车型名称',
        dataIndex: 'name',
        render: val => (
          <Ellipsis length={20} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '车型代码',
        dataIndex: 'code',
      },
      {
        title: '备注',
        dataIndex: 'remark',
        render: (val: any) => (
          <Ellipsis length={10} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: val => (
          <Ellipsis length={20} tooltip>
            {moment(val).format('YYYY-MM-DD HH:mm:ss')}
          </Ellipsis>
        ),
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        // [{key: 1, value: '华为'}， {key: 2, value: '博泰'}]
        // ob= {1： {key: 1, value: '华为'}, 2:{key: 2, value: '博泰'} }
        // ob[value].

        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        initialValue: 'MATC',
        selectOptions: [
          { value: 'MATC', label: '猛士科技' },
          // { value: '1', label: '失败' },
          // { value: '2', label: '异常' },
        ],
        key: 'brandId',
        rules: [{ required: true, message: '品牌为必选项！' }],
      },
      {
        type: 'input',
        title: '车型名称',
        key: 'name',
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'type/getFetchPage', url: '/basedata/type' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: '100%' }}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(Type);
